<template>
  <div>
    <el-form ref="editForm" :rules="rules" :model="editForm" label-width="80px">
      <el-form-item label="商品编号" prop="shopNumber">
        <el-input readonly v-model="editForm.shopNumber"></el-input>
      </el-form-item>
      <el-form-item label="商品名称" prop="shopName">
        <el-input v-model="editForm.shopName"></el-input>
      </el-form-item>
      <el-form-item label="商品价格" prop="shopPrice">
        <el-input v-model="editForm.shopPrice"></el-input>
      </el-form-item>
      <el-form-item label="商品类型" prop="shopType">
        <el-select v-model="editForm.shopType" placeholder="请选择商品类型">
          <el-option v-for="i in shopTypes" :label="i.name" :value="i.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品产地" prop="shopAddr">
        <el-input v-model="editForm.shopAddr"></el-input>
      </el-form-item>
      <el-form-item label="商品规格" prop="shopUnit">
        <el-input v-model="editForm.shopUnit"></el-input>
      </el-form-item>
      <el-form-item label="商品描述">
        <el-input type="textarea" v-model="editForm.shopRemark"></el-input>
      </el-form-item>
      <el-form-item label="上传图片">
        <el-upload
          list-type="picture-card"
          action="#"
          :auto-upload="false"
          :accept="accept"
          :file-list="fileList"
          :on-change="changeImag"
          :before-remove="beforeRemove"
          :on-exceed="handleExceed">
          <i class="el-icon-plus"></i>
        </el-upload>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm('editForm')">确认修改</el-button>
        <el-button @click="resetForm">取消</el-button>
      </span>
  </div>
</template>

<script>
  export default {
    name: "EditShop",
    data() {
      return {
        dialogVisible: false,//模态框状态
        accept: ".jpg,.png",//上传格式限制
        editForm: {id:""},
        fileList: [],//文件集合
        shopTypes: [],//加载商品分类
        rules: {
          shopName: [
            {required: true, message: '请输入商品名称', trigger: 'blur'}
          ],
          shopPrice: [
            {required: true, message: '请输入商品价格', trigger: 'blur'},
            {
              pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
              message: '请输入正确金额格式,可保留两位小数'
            },
          ],
          shopType: [{required: true, message: '请选择商品类型', trigger: 'change'}],
          shopAddr: [{required: true, message: '请输入商品地址', trigger: 'blur'}],
          shopUnit: [
            {required: true, message: '请输入商品规格', trigger: 'blur'},
            {min: 1, max: 2, message: '长度在 1 到 2 个字符', trigger: 'blur'}
          ]
        },//表单规则
      }
    },
    methods: {
      getShopTypes() {
        //获取类别
        this.$axios.get("shopType/shopType.action")
          .then(res => {
            this.shopTypes = res.data;
          })
          .catch(err => {
            this.$message.warning(err);
          })

      },
      getData(id) {
        this.$axios
          .get("shop/queryShopById.action/" + id)
          .then((res) => {
            this.editForm = res.data;
              res.data.imags.forEach(item => {
                this.fileList.push({
                  name: item.imagUrl,
                  raw: '',
                  url: "http://127.0.0.1:9090/demo/" + item.imagUrl
                })
              });
          })
          .catch((err) => {
            alert(err);
          });
      },
      changeImag(file, fileList) {
        //获取文件信息
        this.fileList = fileList;
      },
      submitForm(formName) {
        //提交修改表单
        this.$refs[formName].validate((valid) => {
          if (valid) {
            var formData = new FormData();
            //组装普通数据
            Object.keys(this.editForm).forEach((key) => {
              if (key!="imags" && key!="type" && key!="shopUpnum"){
                formData.append(key, this.editForm[key]);
              }
            });
            //组装文件数据
            this.fileList.forEach(item => {
              if (item.raw == '') {
                formData.append('filenames', item.name)  //db中保存的文件数据
              } else {
                formData.append('files', item.raw)  //新选择的文件
              }
            });
            //真正提交
            this.sendFile(formData);
          } else {
            this.$message.error('error submit!!');
            return false;
          }
        });

      },
      sendFile(data) {
        this.$axios({
          method: 'post',
          url: "shop/editShop.action",
          data: data,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
          if (res.data.code > 0) {
            this.$message.success(res.data.msg);
            this.$refs["editForm"].resetFields();
            this.fileList = [];
            this.$parent.$parent.dialogVisible = false;
            this.$parent.$parent.getShopData();
          } else {
            this.$message.error(res.data.msg)
          }
        }).catch(err => {
          this.$message.error(err);
        })
      },
      resetForm() {
        this.fileList = [];
        this.$refs["editForm"].resetFields();
        this.$parent.$parent.dialogVisible = false;
      },
      handleExceed(files, fileList) {
        this.$message.warning(`当前限制选择 6 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length} 个文件`)
      },
      beforeRemove(file, fileList) {
        this.fileList = fileList;
      }
    },
    created() {
      this.getShopTypes();
    }
  }
</script>

<style scoped>

</style>
